var express = require("express");
var app = express();
var router = express.Router();
var path = require("path");
let { getPuzzleUserinfo } = require("../../../../config/puzzle");
var UserService = require(path.join(process.cwd(), "services/UserService"));
// 初始化 前端登录 userpassport 策略
user_passport = require("../../../../modules/userpassport");
// 创建用户
router.post(
  "/",
  // 验证参数
  function (req, ress, next) {
    let encryptedData = req.body.encryptedData; //获取小程序传来的encryptedData
    let iv = req.body.iv; //获取小程序传来的iv
    let code = req.body.code; //获取小程序传来的code
    let appid = "wx1d7ad192c3fc0d81"; //自己小程序后台管理的appid，可登录小程序后台查看
    let secret = "3e86acc1ea05e3a2673be21cf55fb7df"; //小程序后台管理的secret，可登录小程序后台查看
    let grant_type = "authorization_code"; // 授权（必填）默认值
    //请求获取openid
    let url =
      "https://api.weixin.qq.com/sns/jscode2session?grant_type=" +
      grant_type +
      "&appid=" +
      appid +
      "&secret=" +
      secret +
      "&js_code=" +
      code;
    console.log(url);
    let openid, sessionKey;

    let https = require("https");

    https.get(url, (res) => {
      res
        .on("data", (d) => {
          console.log("返回的信息: ", JSON.parse(d));
          openid = JSON.parse(d).openid; //得到openid
          sessionKey = JSON.parse(d).session_key; //得到session_key
          //解密数据 返回真实的用户信息 只能拿到头像和昵称
          const userinfo = getPuzzleUserinfo(sessionKey, encryptedData, iv);
          // 将内容openid和用户信息userinfo封装成一个数据模型 准备传回数据库
          console.log(openid, userinfo);
          UserService.createUser(userinfo, (err, data) => {
            UserService.login(openid, (err, data) => {
              if (err) {
                ress.sendResult(null, 400, err);
              } else {
                console.log(data, "kkkk");
                data.avatar = userinfo.avatarUrl;
                ress.sendResult(data, 200, "登录成功");
                //需要拿到最新的token返回
              }
            });
          });
          // const userinfoSQLData = userinfoSQLModels(userinfo, openid)
          // const userinfoResData = userinfoResModels(userinfo)
          //返回数据
        })
        .on("error", (e) => {
          console.error(e);
        });
    });
  }
);

module.exports = router;
